﻿using Cysharp.Threading.Tasks;
using UnityEngine;
using YooAsset;

namespace Client.Base
{
    public class FsmRequestPackageVersion : PatchState
    {
        private bool isSucc = true;
        public override async void OnEnter()
        {
            this.Log("[Patch] FsmRequestPackageVersion.");
            isSucc = true;
            string[] packages = AppInfo.Packages;
            for (int i = 0; i < packages.Length; i++)
                await UpdatePackageVersion(packages[i]);
            if (!isSucc)
            { 
                PatchHandle.Instance.ShowErrorMessage("初始化失败(401)");
                return;
            }
            PatchHandle.Instance.Change<FsmUpdatePackageManifest>();
        }

        private async UniTask UpdatePackageVersion(string packageName)
        {
            var package = YooAssets.GetPackage(packageName);
            var operation = package.RequestPackageVersionAsync();
            await operation.ToUniTask();
            if(operation.Status != EOperationStatus.Succeed)
            {
                isSucc = false;
                this.Log($"[Patch]: Fail ！-> pk:{package} , error : {operation.Error}");
            }
            else
            {
                PatchHandle.Instance.SetPackageVersion(packageName, operation.PackageVersion);
            }
        }
    }

}
